<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\BusinessException;
use App\Http\Controllers\Controller;
use App\Models\AssetModel;
use App\Models\GoodsPicPrimaryModel;
use App\Utils\ControllerModelTrait;
use App\Utils\ResponseEnum;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends ApiController
{
    use ControllerModelTrait;

    /**
     * 获取附件列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getAssetList(Request $request): JsonResponse
    {
        $paginate = $this->getPagedData(AssetModel::getModel($request), $request);
        return $this->successPaginate($paginate);
    }

    /**
     * 获取商品压缩包
     * @return JsonResponse
     * @throws BusinessException
     */
    public function getGoodsAsset(): JsonResponse
    {
        $goods_id = $this->verifyId('id');
        $asset = AssetModel::where('goods_id', $goods_id)->where('type', 'zip')->first();
        if ($asset) {
            $goods = GoodsPicPrimaryModel::where('ID', $goods_id)->select(['ID', 'PName', 'Path', 'FName', 'IsEncry'])->first();
            $asset->coverImage = Controller::getImageFullUrl($goods);
            $asset->file = 'https://cms.toysmodel.cn:11443/storage/' . $asset->file;
        }
        return $this->success($asset);
    }

    /**
     * 上传
     * @param Request $request
     * @return JsonResponse
     */
    public function upload(Request $request): JsonResponse
    {
        $files = $request->file();
        $data = [];
        $disk = Storage::disk('public');
        foreach ($files as $file) {
            if (!$file->isValid())
                return $this->fail(ResponseEnum::CLIENT_DELETED_ERROR);
            $ext = $file->getClientOriginalExtension();
            $path = in_array($ext, ['jpg', 'png', 'gif']) ? 'images' : 'files';
            $saveFile = $path. DIRECTORY_SEPARATOR . date('Ymd') . DIRECTORY_SEPARATOR . uniqid().'.'.$ext;
            $disk->put($saveFile, file_get_contents($file->getRealPath()));
            $data[] = ['path' => $saveFile, 'ext' => $ext];
        }
        return $this->success($data);
    }
}
